package com.rover.system.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.grid.DataGrid;
import com.rover.system.entity.User;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.common.Common;
import com.grid.Page;
import com.rover.system.dao.BaseDao;
import com.rover.system.entity.UserLog;

@Service("userLogService")
@Transactional
public class UserLogService{

	@Autowired
	private BaseDao dao;
	
	@Transactional(readOnly = true)
    public DataGrid query(Page page,Map<String, Object> params,List<User> users, List<Integer> ids, String hql){
        DataGrid dataGrid=new DataGrid();
		SimpleDateFormat sdf = new SimpleDateFormat(
		"yyyy-MM-dd hh:mm:ss");
		Long count = Common.INIT_LONG;
		String hql2 = "";
		for(int i = 0;i<ids.size();i++){
			if(i == ids.size() - 1){
				hql2 = hql2 + "tuser='" + ids.get(i) + "'";	
				break;
			}
			hql2 = hql2 + "tuser='" + ids.get(i) + "' or ";
		}
		List<UserLog> logs = dao.findPageHql("from UserLog where " + hql2,page.getPageNo(),page.getPageSize());
		count = dao.countHql("select count(*) from UserLog where " + hql2,null);
		for(UserLog log : logs){
			log.setLoginName(log.getTuser().getLoginName());
			log.setName(log.getTuser().getName());
			log.setTuser(null);
			Date operateDte = log.getOperateDate();
			String date = sdf.format(operateDte);
			log.setOperateDateView(date);
		}
        dataGrid.setResult(logs);
        dataGrid.setTotalCount(count);
	    return dataGrid;
	}
	
	//记录日志
	@Transactional
	public void log(HttpServletRequest request,User user, String operation){
		UserLog userLog = new UserLog();
		userLog.setTuser(user);
		userLog.setIpAddress(getIpAddr(request));
		userLog.setOperateDate(new Date());
		userLog.setOperation(operation);
        dao.save(userLog);
	}
	
	//获取IP地址，考虑反向代理情况
	private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
           ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
           ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
	}
	
	@Transactional
	public void deleteLogs(User user){
//		Query q = userLogDao.getCurrentSession().createQuery(
//						"delete from UserLog where tuser=:tuser");
//		q.setParameter("tuser", user);
//		q.executeUpdate();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("tuser", user);
        dao.executeHql("delete from UserLog where tuser=:tuser", params);
	}
	
}
